import os
import pathlib
import shutil
import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import yaml

class FileCopyApp:
    def __init__(self, root):
        self.root = root
        self.root.title("文件/文件夹批量复制工具")
        self.root.geometry("700x500")
        self.root.resizable(True, True)
        
        # 源文件夹和目标文件夹路径
        self.source_folder = tk.StringVar()
        self.target_folder = tk.StringVar()
        
        # 创建界面组件
        self.create_widgets()
        
        # 初始化路径
        self.current_path = str(pathlib.Path(__file__).parent.absolute().resolve())
        self.source_folder.set(self.current_path)
        self.target_folder.set(self.current_path)

    def create_widgets(self):
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 源文件夹选择
        ttk.Label(main_frame, text="源文件夹 (包含要复制的内容):").pack(anchor=tk.W, pady=(0, 5))
        source_frame = ttk.Frame(main_frame)
        source_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Entry(source_frame, textvariable=self.source_folder).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))
        ttk.Button(source_frame, text="浏览...", command=self.select_source).pack(side=tk.RIGHT)
        
        # 目标父文件夹选择
        ttk.Label(main_frame, text="目标父文件夹 (要复制到其子文件夹):").pack(anchor=tk.W, pady=(0, 5))
        target_frame = ttk.Frame(main_frame)
        target_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Entry(target_frame, textvariable=self.target_folder).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))
        ttk.Button(target_frame, text="浏览...", command=self.select_target).pack(side=tk.RIGHT)
        
        # 操作按钮
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Button(btn_frame, text="开始复制", command=self.start_copy).pack(side=tk.LEFT, padx=(0, 10))
        ttk.Button(btn_frame, text="清除日志", command=self.clear_log).pack(side=tk.LEFT)
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        ttk.Label(main_frame, text="复制进度:").pack(anchor=tk.W, pady=(0, 5))
        self.progress_bar = ttk.Progressbar(main_frame, variable=self.progress_var, maximum=100)
        self.progress_bar.pack(fill=tk.X, pady=(0, 10))
        
        # 日志区域
        ttk.Label(main_frame, text="操作日志:").pack(anchor=tk.W, pady=(0, 5))
        log_frame = ttk.Frame(main_frame)
        log_frame.pack(fill=tk.BOTH, expand=True)
        
        scrollbar = ttk.Scrollbar(log_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.log_text = tk.Text(log_frame, wrap=tk.WORD, yscrollcommand=scrollbar.set, state=tk.DISABLED)
        self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.config(command=self.log_text.yview)

    def select_source(self):
        folder = filedialog.askdirectory(initialdir=self.source_folder.get(), title="选择源文件夹")
        if folder:
            self.source_folder.set(folder)

    def select_target(self):
        folder = filedialog.askdirectory(initialdir=self.target_folder.get(), title="选择目标父文件夹")
        if folder:
            self.target_folder.set(folder)

    def log(self, message):
        """在日志区域添加消息"""
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)  # 滚动到最后一行
        self.log_text.config(state=tk.DISABLED)
        self.root.update_idletasks()  # 刷新界面

    def clear_log(self):
        """清除日志内容"""
        self.log_text.config(state=tk.NORMAL)
        self.log_text.delete(1.0, tk.END)
        self.log_text.config(state=tk.DISABLED)

    def start_copy(self):
        """开始复制操作"""
        source = self.source_folder.get()
        target_parent = self.target_folder.get()
        
        # 验证路径
        if not os.path.isdir(source):
            messagebox.showerror("错误", "源文件夹不存在或无效！")
            return
            
        if not os.path.isdir(target_parent):
            messagebox.showerror("错误", "目标父文件夹不存在或无效！")
            return
        
        # 收集要复制的项目
        try:
            items_to_copy = [os.path.join(source, item) for item in os.listdir(source)]
            if not items_to_copy:
                messagebox.showwarning("警告", "源文件夹中没有可复制的内容！")
                return
        except Exception as e:
            messagebox.showerror("错误", f"读取源文件夹失败: {str(e)}")
            return
        
        # 收集目标子文件夹
        try:
            target_folders = [
                os.path.join(target_parent, item) 
                for item in os.listdir(target_parent) 
                if os.path.isdir(os.path.join(target_parent, item))
            ]
            if not target_folders:
                messagebox.showwarning("警告", "目标父文件夹中没有子文件夹！")
                return
        except Exception as e:
            messagebox.showerror("错误", f"读取目标父文件夹失败: {str(e)}")
            return
        
        # 开始复制
        self.log("===== 开始复制操作 =====")
        self.log(f"源文件夹: {source}")
        self.log(f"目标父文件夹: {target_parent}")
        self.log(f"发现 {len(items_to_copy)} 个待复制项，{len(target_folders)} 个目标子文件夹")
        
        total_operations = len(items_to_copy) * len(target_folders)
        completed_operations = 0
        
        for i, target_folder in enumerate(target_folders, 1):
            self.log(f"\n处理文件夹 {i}/{len(target_folders)}: {target_folder}")
            
            for j, item in enumerate(items_to_copy, 1):
                item_name = os.path.basename(item)
                target_path = os.path.join(target_folder, item_name)
                
                try:
                    # 确保目标目录存在
                    os.makedirs(os.path.dirname(target_path), exist_ok=True)
                    
                    if os.path.isfile(item):
                        # 处理YAML文件
                        if item_name.lower().endswith(('.yaml', '.yml')):
                            with open(item, 'r', encoding='utf-8') as f:
                                content = f.read()
                            with open(target_path, 'w', encoding='utf-8') as f:
                                f.write(content)
                            self.log(f"  YAML文件 {j}/{len(items_to_copy)}: {item_name} [成功]")
                        else:
                            shutil.copy2(item, target_path)
                            self.log(f"  文件 {j}/{len(items_to_copy)}: {item_name} [成功]")
                    elif os.path.isdir(item):
                        if not os.path.exists(target_path):
                            shutil.copytree(item, target_path)
                            self.log(f"  目录 {j}/{len(items_to_copy)}: {item_name} [成功]")
                        else:
                            self.log(f"  目录 {j}/{len(items_to_copy)}: {item_name} [已存在，跳过]")
                    else:
                        self.log(f"  未知类型 {j}/{len(items_to_copy)}: {item_name} [跳过]")
                        
                except Exception as e:
                    self.log(f"  错误 {j}/{len(items_to_copy)}: {item_name} → {str(e)}")
                
                # 更新进度
                completed_operations += 1
                progress = (completed_operations / total_operations) * 100
                self.progress_var.set(progress)
                self.root.update_idletasks()
        
        self.log("\n===== 操作完成 =====")
        messagebox.showinfo("完成", "所有复制操作已完成！")
        self.progress_var.set(100)

if __name__ == "__main__":
    root = tk.Tk()
    app = FileCopyApp(root)
    root.mainloop()